<template>
  <view class="custom-tabbar">
    <view 
      v-for="item in tabList" 
      :key="item.pagePath"
      class="tab-item"
      :class="{ active: currentPath === item.pagePath }"
      @click="switchTab(item.pagePath)"
    >
      <text class="tab-icon">{{ item.icon }}</text>
      <text class="tab-text">{{ item.text }}</text>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

const props = defineProps({
  current: {
    type: String,
    default: ''
  }
})

const currentPath = ref('/pages/index/index')

function updateCurrentPath() {
  const pages = getCurrentPages()
  if (pages.length > 0) {
    const route = pages[pages.length - 1].route
    currentPath.value = '/' + route
  }
}

onMounted(() => {
  updateCurrentPath()
  // 监听路由变化
  // #ifdef H5
  // H5 端可以通过监听路由变化更新
  // #endif
})

const tabList = [
  {
    pagePath: '/pages/index/index',
    text: '首页',
    icon: '🏠'
  },
  {
    pagePath: '/pages/favorites/favorites',
    text: '收藏',
    icon: '❤️'
  },
  {
    pagePath: '/pages/profile/profile',
    text: '我的',
    icon: '👤'
  }
]

function switchTab(path) {
  if (currentPath.value === path) {
    return // 已经在当前页面
  }
  
  currentPath.value = path
  
  // H5 端使用 navigateTo，小程序端会自动使用 switchTab
  // #ifdef H5
  uni.navigateTo({
    url: path,
    fail: () => {
      // 导航失败时回退
      updateCurrentPath()
    }
  })
  // #endif
  
  // #ifdef MP-WEIXIN
  uni.switchTab({
    url: path
  })
  // #endif
}
</script>

<style scoped>
.custom-tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  height: 50px;
  background-color: #fff;
  border-top: 1rpx solid #e5e5e5;
  z-index: 1000;
  padding-bottom: env(safe-area-inset-bottom);
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 5rpx 0;
}

.tab-icon {
  font-size: 40rpx;
  margin-bottom: 4rpx;
}

.tab-text {
  font-size: 20rpx;
  color: #7A7E83;
}

.tab-item.active .tab-text {
  color: #007AFF;
  font-weight: 500;
}
</style>

